// 创建路由与hash
import { createRouter, createWebHashHistory } from 'vue-router'
// 引入路由图层
import Layout from '../components/Layout/index.vue'
// 定义路由规则
const routes = [
  { path: '/', name: 'mian', redirect: '/mian' },
  {
    path: '/login',
    name: '登录',
    component: () => import('../views/Login.vue'),
  },
  {
    path: '/enrole',
    name: '注册',
    component: () => import('../views/Enrole.vue'),
  },
  {
    path: '/mian',
    name: '页面主体',
    component: Layout,
    redirect: '/home',
    children: [{ path: '/home', component: () => import('../views/Home.vue') }],
  },
  /* 
  注意:子路由不要加/
  */
  {
    path: '/articles',
    name: '文章管理',
    component: Layout,
    children: [
      {
        path: 'article-list',
        name: '文章列表',
        component: () => import('../views/ArticlesList.vue'),
      },
    ],
  },
  {
    path: '/users',
    name: '用户管理',
    component: Layout,
    children: [
      {
        path: 'user-list',
        name: '用户列表',
        component: () => import('../views/UsersList.vue'),
      },
    ],
  },
  {
    path: '/categories',
    name: '分类管理',
    component: Layout,
    children: [
      {
        path: 'category-list',
        name: '分类列表',
        component: () => import('../views/CategoriesList.vue'),
      },
    ],
  },
  {
    path: '/comments',
    name: '评论管理',
    component: Layout,
    children: [
      {
        path: 'comment-list',
        name: '评论列表',
        component: () => import('../views/CommentList.vue'),
      },
    ],
  },
  // 动态路由404,https://router.vuejs.org/zh/guide/essentials/dynamic-matching.html#%E6%8D%95%E8%8E%B7%E6%89%80%E6%9C%89%E8%B7%AF%E7%94%B1%E6%88%96-404-not-found-%E8%B7%AF%E7%94%B1
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('../views/NotFound.vue'),
  },
]
const router = createRouter({
  history: createWebHashHistory(),
  routes,
})
// 路由导航守卫
router.beforeEach((to, from, next) => {
  /* 
  1.to:将要访问的路径
  2.from:表示从哪个路径跳转过来的
  3.next:是一个表示路由导航守卫放行的函数
  */
  //  如果访问登录/注册页面则可以直接放行
  if (to.path === '/login' || to.path === '/enrole') return next()
  // 如果不是访问登录页面,则先验证是否拿到了token
  const token = sessionStorage.getItem('isLogin')
  // 没拿到就返回登录页面
  if (!token) return next('/login')
  // 拿到就直接放行
  next()
})
export default router
